package utilities.print.menu.execute.userPortal;

import employee.User;
import utilities.JDBC.Database;
import utilities.JDBC.sql.SelectUserName;
import utilities.print.log.LogMessage;
import utilities.print.menu.MenuExecute;
import utilities.print.menu.execute.Verify;

import java.util.Scanner;

import static utilities.print.menu.Menu.line;

public class Add implements MenuExecute {
    private final Database<Object> database = new Database<>();

    private final LogMessage Log = new LogMessage("userPortal.add");

    /**
     * 启动菜单功能类方法
     * @throws Exception 可能产生的异常
     */
    @Override
    public void execute() throws Exception {
        Scanner in = new Scanner(System.in);
        User user = new User();

        System.out.println("添加账号");
        line();
        PrintList.printDatabaseUserInfo();
        //添加账号名字
        System.out.print("输入添加的账号名: ");
        user.setName(in.next());
        while (database.executeSelect(new SelectUserName(user.getName())).next()){
            System.out.println("账号名重复!");
            System.out.print("输入账号名: ");
            user.setName(in.next());
        }

        //账号密码
        line();
        System.out.print("输入添加的账号密码: ");
        user.setPassword(in.next());
        while (user.getPassword().isEmpty()){
            System.out.println("密码不能为空!");
            System.out.print("输入账号密码: ");
            user.setPassword(in.next());
        }


        //保存数据库
        line();
        if (Verify.isConfirm()){
            final String name = user.getName();
            final String password = user.getPassword();
            database.executeUpdate(
                    connection -> connection.prepareStatement("insert into userinfo(userName,userPassword) value('" +
                            name +
                            "','" +
                            password +
                            "')"
                    )
            );
            System.out.println("添加成功!");
            line();
            System.out.printf("添加的账号信息 名字:%s,密码:%s\n" ,name ,password);
            Log.print("向数据库添加账号信息: " + user);
            Log.closeOutputFile();

            database.close();
            line();

            PrintList.printDatabaseUserInfo();
        }else {
            System.out.println("添加失败!");
            line();
        }
        Verify.pressKey("输入任意内容返回上级页面");
    }
}
